using UnityEngine;
using System.Collections;

public class GUIObject : MonoBehaviour {
	
	public Material GUIMaterial;
	public Vector2 localSize = new Vector2(100,100);
	public Vector2[] UV = new Vector2[] {
		
		new Vector2(0.0f, 0.0f),
		new Vector2(0.0f, 1f),
		new Vector2(1f, 0.0f),
		new Vector2(1f, 1f)
		
	};
	public float textureHeight;
	public float textureWidth;
	public float rowsCount;
	public float columnsCount;
	
	int[] actualFrame = new int[2];
	
	float frameWidth;
	float frameHeigth;
	
	protected void SetFrame(int row, int column){
		UV[2].x = (frameWidth * column);
		UV[2].y = (frameHeigth * row);
		
		UV[3].x = UV[2].x + frameWidth;
		UV[3].y = UV[2].y;
		
		UV[0].x = UV[2].x;
		UV[0].y = UV[2].y + frameHeigth;
		
		UV[1].x = UV[2].x + frameWidth;
		UV[1].y = UV[2].y + frameHeigth;
		mesh.uv = UV;
		
	}
	
	Mesh mesh;
	Vector3[] vertices;
	void Awake () {
		//Debug.Log("Awake GUIOBJECT");
		frameWidth = (textureWidth / columnsCount) / textureWidth;
		frameHeigth = (textureHeight / rowsCount) / textureHeight;
		
		mesh = new Mesh();
		vertices = new Vector3[4];
				
		MeshFilter filter = this.gameObject.AddComponent<MeshFilter>();
				
		vertices[0] = new Vector3(-localSize.x / 2.0f, localSize.y / 2.0f, 0f);
		vertices[1] = new Vector3(localSize.x / 2.0f, localSize.y / 2.0f, 0f);
		vertices[2] = new Vector3(-localSize.x / 2.0f, -localSize.y / 2.0f, 0f);
		vertices[3] = new Vector3(localSize.x / 2.0f, -localSize.y / 2.0f, 0f);
		
		mesh.vertices = vertices;
		
		int[] indices = new int[] {0,1,2,2,1,3};
		
		mesh.SetIndices(indices, MeshTopology.Triangles, 0);
		mesh.uv = UV;
		
		filter.sharedMesh = mesh;
		
		MeshRenderer meshRenderer = this.gameObject.AddComponent<MeshRenderer>();
		
		meshRenderer.sharedMaterial = GUIMaterial;
		
		SetFrame(0,0);
		
	}
	
	void OnDrawGizmos(){
		Gizmos.color = Color.white;
		
		Vector3 zeroZero = transform.position - new Vector3(transform.localScale.x/2 *localSize.x * transform.parent.localScale.x, -transform.localScale.y/2 *localSize.y* transform.parent.localScale.y,0)  ;
		
		Gizmos.DrawLine(zeroZero, zeroZero + new Vector3(transform.localScale.x,0,0) *localSize.x* transform.parent.localScale.x);
		Gizmos.DrawLine(zeroZero, zeroZero - new Vector3(0,transform.localScale.y,0) *localSize.y* transform.parent.localScale.y);
		Gizmos.DrawLine(zeroZero + new Vector3(transform.localScale.x* transform.parent.localScale.x,0,0)*localSize.x, zeroZero + new Vector3(transform.localScale.x* localSize.x* transform.parent.localScale.x, -transform.localScale.y *localSize.y* transform.parent.localScale.y,0) );
		Gizmos.DrawLine(zeroZero - new Vector3(0,transform.localScale.y* transform.parent.localScale.y,0)*localSize.y, zeroZero + new Vector3(transform.localScale.x * localSize.x* transform.parent.localScale.x, -transform.localScale.y *localSize.y* transform.parent.localScale.y,0) );
		
	}
	
}
